/*
 *    Copyright (c) 2018-2025, st All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: st
 */

package com.mkh.st.common.security.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.mkh.st.admin.api.dto.UserInfo;
import com.mkh.st.admin.api.entity.SysTenant;
import com.mkh.st.admin.api.entity.SysUser;
import com.mkh.st.admin.api.feign.ISysTenantProvider;
import com.mkh.st.admin.api.feign.ISysUserProvider;
import com.mkh.st.admin.api.vo.UserTenantVO;
import com.mkh.st.common.core.constant.CacheConstants;
import com.mkh.st.common.core.constant.CommonConstants;
import com.mkh.st.common.core.constant.SecurityConstants;
import com.mkh.st.common.core.constant.enums.ResultCodeEnum;
import com.mkh.st.common.core.constant.enums.UserStatusEnum;
import com.mkh.st.common.core.util.R;
import com.mkh.st.common.security.exception.LoginAuthException;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 用户详细信息
 *
 * @author st
 */
@Slf4j
@RequiredArgsConstructor
public class DaoismUserDetailsServiceImpl implements DaoismUserDetailsService {

	private final ISysUserProvider sysUserProvider;

	private final ISysTenantProvider sysTenantProvider;

	private final CacheManager cacheManager;

	/**
	 * 用户密码登录
	 * @param phone 用户手机号
	 * @returnead
	 * @throws UsernameNotFoundException
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String phone) {//用户手机号登录
//		Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS);
//		if (cache != null && cache.get(phone) != null) {
//			return  cache.get(phone, DaoismUser.class);
//		}
		R<UserInfo> result = sysUserProvider.info(phone);
		UserDetails userDetails = getUserDetails(result);
//		cache.put(phone, userDetails);
		return userDetails;
	}

	/**
	 * 根据社交登录code 登录
	 * @param inStr TYPE@CODE
	 * @return UserDetails
	 * @throws UsernameNotFoundException
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserBySocial(String inStr) {
		return getUserDetails(sysUserProvider.social(inStr));
	}

	/**
	 * 构建userdetails
	 * @param result 用户信息
	 * @return
	 */
	private UserDetails getUserDetails(R<UserInfo> result) {
		if (result == null || result.getData() == null) {
			throw new UsernameNotFoundException("用户不存在");
		}
		UserInfo info = result.getData();
		Set<String> dbAuthsSet = new HashSet<>();
		if(!CommonConstants.ONE.equals(info.getSysUser().getNotShow()) &&ArrayUtil.isEmpty(info.getRoles())){
			throw new LoginAuthException(ResultCodeEnum.USER_NO_ROLE);
		}
		SysTenant sysTenant =sysTenantProvider.getInfoById(info.getSysUser().getTenantId());
		if(ObjectUtil.isNotNull(sysTenant) && sysTenant.getStatus()== CommonConstants.ZERO){
			throw new LoginAuthException(ResultCodeEnum.USER_TENANT_LOCK);
		}
		if (ArrayUtil.isNotEmpty(info.getRoles())) {
			// 获取角色
			Arrays.stream(info.getRoles()).forEach(roleId -> dbAuthsSet.add(SecurityConstants.ROLE + roleId));
			// 获取资源
			if(ArrayUtil.isNotEmpty(info.getPermissions())){
				dbAuthsSet.addAll(Arrays.asList(info.getPermissions()));
			}
		}
		Collection<? extends GrantedAuthority> authorities = AuthorityUtils
				.createAuthorityList(dbAuthsSet.toArray(new String[0]));
		SysUser user = info.getSysUser();

		// 构造security用户
		return new DaoismUser(user.getUserId(),user.getUsername(),user.getAvatar(),user.getTenantId(),
				user.getPhone(),SecurityConstants.BCRYPT + user.getPassword(),
				user.getNormalFlag()== UserStatusEnum.NORMAL.getStatus(), LocalDateTime.now().isAfter(user.getBeginTime())&&LocalDateTime.now().isBefore(user.getEndTime()), true,
				user.getNormalFlag()!=UserStatusEnum.LOCK.getStatus(),authorities,info.getDataScopes());
	}

}
